# -*- coding: utf-8 -*-
"""
桌面管理器 - 半透明悬浮窗口 + 透明分类窗格
参考360桌面助手的设计精髓
"""

import tkinter as tk
from tkinter import ttk, messagebox
import os
import shutil
import json
from datetime import datetime
import threading
import sys
from pathlib import Path
from config import get_file_categories, get_setting, set_setting

class FileItem:
    """文件项类"""
    def __init__(self, file_path, category):
        self.file_path = file_path
        self.category = category
        self.name = os.path.basename(file_path)
        self.icon = self._get_file_icon()
    
    def _get_file_icon(self):
        """根据文件类型获取图标"""
        ext = os.path.splitext(self.name)[1].lower()
        icon_map = {
            '.txt': '📄', '.doc': '📄', '.docx': '📄', '.pdf': '📕',
            '.xls': '📊', '.xlsx': '📊', '.ppt': '📺', '.pptx': '📺',
            '.jpg': '🖼️', '.jpeg': '🖼️', '.png': '🖼️', '.gif': '🖼️',
            '.mp4': '🎬', '.avi': '🎬', '.mkv': '🎬', '.mov': '🎬',
            '.mp3': '🎵', '.wav': '🎵', '.flac': '🎵',
            '.zip': '📦', '.rar': '📦', '.7z': '📦',
            '.exe': '⚙️', '.msi': '⚙️',
            '.lnk': '🔗', '.url': '🔗'
        }
        return icon_map.get(ext, '📄')

class CategoryWindow:
    """分类窗格窗口"""
    def __init__(self, category, files, manager, x=100, y=100):
        self.category = category
        self.files = files
        self.manager = manager
        self.window = tk.Toplevel()
        self.is_minimized = False
        self.is_dragging = False
        self.drag_data = {"x": 0, "y": 0}
        self.setup_window(x, y)
        self.setup_ui()
        
    def setup_window(self, x, y):
        """设置窗口属性"""
        self.window.title(f"{self.category} ({len(self.files)})")
        self.window.geometry(f"200x300+{x}+{y}")
        self.window.configure(bg='#2c3e50')
        
        # 设置窗口属性
        self.window.overrideredirect(True)
        self.window.attributes('-topmost', True)
        self.window.attributes('-alpha', 0.85)
        
        # 绑定拖拽事件
        self.window.bind('<Button-1>', self.start_drag)
        self.window.bind('<B1-Motion>', self.on_drag)
        self.window.bind('<ButtonRelease-1>', self.stop_drag)
        
        # 鼠标悬停效果
        self.window.bind('<Enter>', lambda e: self.window.attributes('-alpha', 0.95))
        self.window.bind('<Leave>', lambda e: self.window.attributes('-alpha', 0.85))
        
    def setup_ui(self):
        """设置用户界面"""
        # 标题栏
        title_frame = tk.Frame(self.window, bg='#34495e', height=30)
        title_frame.pack(fill='x')
        title_frame.pack_propagate(False)
        
        # 分类图标和名称
        category_icons = {
            '文档': '📄', '图片': '🖼️', '视频': '🎬', '音频': '🎵',
            '压缩包': '📦', '程序': '⚙️', '快捷方式': '🔗', '代码': '💻', '字体': '🔤'
        }
        icon = category_icons.get(self.category, '📁')
        
        title_label = tk.Label(title_frame, text=f"{icon} {self.category} ({len(self.files)})",
                              font=('微软雅黑', 10, 'bold'), fg='white', bg='#34495e')
        title_label.pack(side='left', padx=10, pady=5)
        
        # 最小化按钮
        minimize_btn = tk.Button(title_frame, text="─", font=('微软雅黑', 8, 'bold'),
                               fg='white', bg='#34495e', relief='flat', width=2,
                               command=self.toggle_minimize)
        minimize_btn.pack(side='right', padx=2, pady=2)
        
        # 关闭按钮
        close_btn = tk.Button(title_frame, text="×", font=('微软雅黑', 8, 'bold'),
                            fg='white', bg='#e74c3c', relief='flat', width=2,
                            command=self.close_window)
        close_btn.pack(side='right', padx=2, pady=2)
        
        # 文件列表区域
        self.files_frame = tk.Frame(self.window, bg='#2c3e50')
        self.files_frame.pack(fill='both', expand=True, padx=5, pady=5)
        
        # 创建滚动区域
        self.canvas = tk.Canvas(self.files_frame, bg='#2c3e50', highlightthickness=0)
        self.scrollbar = ttk.Scrollbar(self.files_frame, orient="vertical", command=self.canvas.yview)
        self.scrollable_frame = tk.Frame(self.canvas, bg='#2c3e50')
        
        self.scrollable_frame.bind(
            "<Configure>",
            lambda e: self.canvas.configure(scrollregion=self.canvas.bbox("all"))
        )
        
        self.canvas.create_window((0, 0), window=self.scrollable_frame, anchor="nw")
        self.canvas.configure(yscrollcommand=self.scrollbar.set)
        
        # 添加文件项
        self.file_widgets = []
        self.update_file_list()
        
        self.canvas.pack(side="left", fill="both", expand=True)
        self.scrollbar.pack(side="right", fill="y")
        
    def update_file_list(self):
        """更新文件列表"""
        # 清空现有文件项
        for widget in self.file_widgets:
            widget.destroy()
        self.file_widgets.clear()
        
        # 添加文件项
        for i, file_item in enumerate(self.files):
            file_frame = tk.Frame(self.scrollable_frame, bg='#34495e', relief='raised', bd=1)
            file_frame.pack(fill='x', padx=2, pady=2)
            
            # 文件图标和名称
            icon_label = tk.Label(file_frame, text=file_item.icon, font=('微软雅黑', 14),
                                bg='#34495e', fg='white')
            icon_label.pack(side='left', padx=5, pady=5)
            
            name_label = tk.Label(file_frame, text=file_item.name[:15] + "..." if len(file_item.name) > 15 else file_item.name,
                                font=('微软雅黑', 9), bg='#34495e', fg='white', anchor='w')
            name_label.pack(side='left', fill='x', expand=True, padx=5, pady=5)
            
            # 绑定双击打开文件
            file_frame.bind('<Double-Button-1>', lambda e, f=file_item: self.open_file(f))
            icon_label.bind('<Double-Button-1>', lambda e, f=file_item: self.open_file(f))
            name_label.bind('<Double-Button-1>', lambda e, f=file_item: self.open_file(f))
            
            # 绑定右键菜单
            file_frame.bind('<Button-3>', lambda e, f=file_item: self.show_context_menu(e, f))
            
            # 悬停效果
            def on_enter(e, frame=file_frame):
                frame.configure(bg='#3498db')
                for child in frame.winfo_children():
                    child.configure(bg='#3498db')
            
            def on_leave(e, frame=file_frame):
                frame.configure(bg='#34495e')
                for child in frame.winfo_children():
                    child.configure(bg='#34495e')
            
            file_frame.bind('<Enter>', on_enter)
            file_frame.bind('<Leave>', on_leave)
            icon_label.bind('<Enter>', on_enter)
            icon_label.bind('<Leave>', on_leave)
            name_label.bind('<Enter>', on_enter)
            name_label.bind('<Leave>', on_leave)
            
            self.file_widgets.append(file_frame)
    
    def open_file(self, file_item):
        """打开文件"""
        try:
            os.startfile(file_item.file_path)
        except Exception as e:
            messagebox.showerror("错误", f"无法打开文件: {str(e)}")
    
    def show_context_menu(self, event, file_item):
        """显示右键菜单"""
        context_menu = tk.Menu(self.window, tearoff=0)
        context_menu.add_command(label="打开", command=lambda: self.open_file(file_item))
        context_menu.add_command(label="移至其他分类", command=lambda: self.show_move_menu(file_item))
        context_menu.add_command(label="还原到桌面", command=lambda: self.restore_to_desktop(file_item))
        context_menu.add_separator()
        context_menu.add_command(label="删除", command=lambda: self.delete_file(file_item))
        
        try:
            context_menu.tk_popup(event.x_root, event.y_root)
        finally:
            context_menu.grab_release()
    
    def show_move_menu(self, file_item):
        """显示移动到其他分类的菜单"""
        categories = list(get_file_categories().keys()) + ['其他']
        move_menu = tk.Menu(self.window, tearoff=0)
        
        for category in categories:
            if category != self.category:
                move_menu.add_command(label=category, 
                                    command=lambda c=category: self.move_to_category(file_item, c))
        
        # 在鼠标位置显示菜单
        try:
            x, y = self.window.winfo_pointerxy()
            move_menu.tk_popup(x, y)
        finally:
            move_menu.grab_release()
    
    def move_to_category(self, file_item, new_category):
        """移动文件到其他分类"""
        try:
            # 创建新分类目录
            storage_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "桌面收纳空间")
            new_category_path = os.path.join(storage_path, new_category)
            os.makedirs(new_category_path, exist_ok=True)
            
            # 移动文件
            new_file_path = os.path.join(new_category_path, file_item.name)
            if os.path.exists(new_file_path):
                name, ext = os.path.splitext(file_item.name)
                timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                new_name = f"{name}_{timestamp}{ext}"
                new_file_path = os.path.join(new_category_path, new_name)
            
            shutil.move(file_item.file_path, new_file_path)
            
            # 更新文件项
            file_item.file_path = new_file_path
            file_item.category = new_category
            
            # 从当前窗口移除
            self.files.remove(file_item)
            self.update_file_list()
            self.update_title()
            
            # 通知管理器更新其他窗口
            self.manager.refresh_category_windows()
            
        except Exception as e:
            messagebox.showerror("错误", f"移动文件失败: {str(e)}")
    
    def restore_to_desktop(self, file_item):
        """还原文件到桌面"""
        try:
            desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
            desktop_file_path = os.path.join(desktop_path, file_item.name)
            
            # 如果桌面已有同名文件，添加时间戳
            if os.path.exists(desktop_file_path):
                name, ext = os.path.splitext(file_item.name)
                timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                new_name = f"{name}_{timestamp}{ext}"
                desktop_file_path = os.path.join(desktop_path, new_name)
            
            shutil.move(file_item.file_path, desktop_file_path)
            
            # 从列表中移除
            self.files.remove(file_item)
            self.update_file_list()
            self.update_title()
            
            messagebox.showinfo("成功", f"文件已还原到桌面: {os.path.basename(desktop_file_path)}")
            
        except Exception as e:
            messagebox.showerror("错误", f"还原文件失败: {str(e)}")
    
    def delete_file(self, file_item):
        """删除文件"""
        if messagebox.askyesno("确认删除", f"确定要删除文件 '{file_item.name}' 吗？\n此操作不可恢复！"):
            try:
                os.remove(file_item.file_path)
                self.files.remove(file_item)
                self.update_file_list()
                self.update_title()
                messagebox.showinfo("成功", "文件已删除")
            except Exception as e:
                messagebox.showerror("错误", f"删除文件失败: {str(e)}")
    
    def start_drag(self, event):
        """开始拖拽窗口"""
        self.is_dragging = True
        self.drag_data["x"] = event.x
        self.drag_data["y"] = event.y
    
    def on_drag(self, event):
        """拖拽窗口"""
        if self.is_dragging:
            x = self.window.winfo_x() + (event.x - self.drag_data["x"])
            y = self.window.winfo_y() + (event.y - self.drag_data["y"])
            self.window.geometry(f"+{x}+{y}")
    
    def stop_drag(self, event):
        """停止拖拽"""
        self.is_dragging = False
    
    def toggle_minimize(self):
        """切换最小化状态"""
        if self.is_minimized:
            # 展开
            self.window.geometry("200x300")
            self.files_frame.pack(fill='both', expand=True, padx=5, pady=5)
            self.is_minimized = False
        else:
            # 最小化
            self.window.geometry("200x30")
            self.files_frame.pack_forget()
            self.is_minimized = True
    
    def close_window(self):
        """关闭窗口"""
        self.window.destroy()
        if self in self.manager.category_windows:
            self.manager.category_windows.remove(self)
    
    def update_title(self):
        """更新标题"""
        self.window.title(f"{self.category} ({len(self.files)})")

class DesktopManager:
    """桌面管理器主类"""
    def __init__(self):
        self.root = tk.Tk()
        self.category_windows = []
        self.setup_main_window()
        self.setup_ui()
        self.load_existing_files()
        
    def setup_main_window(self):
        """设置主窗口"""
        self.root.title("桌面助手")
        
        # 获取屏幕尺寸
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        
        # 设置窗口大小和位置（右上角）
        window_width = 280
        window_height = 400
        x = screen_width - window_width - 20
        y = 20
        
        self.root.geometry(f"{window_width}x{window_height}+{x}+{y}")
        self.root.configure(bg='#2c3e50')
        
        # 设置窗口属性
        self.root.overrideredirect(True)
        self.root.attributes('-topmost', True)
        self.root.attributes('-alpha', 0.9)
        
        # 绑定拖拽
        self.is_dragging = False
        self.drag_data = {"x": 0, "y": 0}
        self.root.bind('<Button-1>', self.start_drag)
        self.root.bind('<B1-Motion>', self.on_drag) 
        self.root.bind('<ButtonRelease-1>', self.stop_drag)
        
        # 鼠标悬停效果
        self.root.bind('<Enter>', lambda e: self.root.attributes('-alpha', 1.0))
        self.root.bind('<Leave>', lambda e: self.root.attributes('-alpha', 0.9))
        
    def setup_ui(self):
        """设置用户界面"""
        # 标题栏
        title_frame = tk.Frame(self.root, bg='#34495e', height=40)
        title_frame.pack(fill='x')
        title_frame.pack_propagate(False)
        
        title_label = tk.Label(title_frame, text="🖥️ 桌面助手", 
                              font=('微软雅黑', 14, 'bold'), fg='white', bg='#34495e')
        title_label.pack(side='left', padx=10, pady=10)
        
        # 关闭按钮
        close_btn = tk.Button(title_frame, text="×", font=('微软雅黑', 12, 'bold'),
                            fg='white', bg='#e74c3c', relief='flat', width=3,
                            command=self.close_application)
        close_btn.pack(side='right', padx=5, pady=5)
        
        # 设置按钮
        settings_btn = tk.Button(title_frame, text="⚙", font=('微软雅黑', 12, 'bold'),
                               fg='white', bg='#3498db', relief='flat', width=3,
                               command=self.show_settings)
        settings_btn.pack(side='right', padx=2, pady=5)
        
        # 主要功能区域
        main_frame = tk.Frame(self.root, bg='#2c3e50')
        main_frame.pack(fill='both', expand=True, padx=10, pady=10)
        
        # 桌面状态显示
        status_frame = tk.LabelFrame(main_frame, text="桌面状态", font=('微软雅黑', 10, 'bold'),
                                   fg='white', bg='#2c3e50')
        status_frame.pack(fill='x', pady=(0, 10))
        
        self.status_label = tk.Label(status_frame, text="点击扫描桌面", font=('微软雅黑', 9),
                                   fg='#ecf0f1', bg='#2c3e50', justify='left')
        self.status_label.pack(padx=10, pady=5)
        
        # 功能按钮
        btn_frame = tk.Frame(main_frame, bg='#2c3e50')
        btn_frame.pack(fill='x', pady=5)
        
        scan_btn = tk.Button(btn_frame, text="🔍 扫描桌面", font=('微软雅黑', 11, 'bold'),
                           bg='#3498db', fg='white', relief='flat', 
                           command=self.scan_desktop)
        scan_btn.pack(fill='x', pady=2)
        
        organize_btn = tk.Button(btn_frame, text="✨ 一键整理", font=('微软雅黑', 11, 'bold'),
                               bg='#e74c3c', fg='white', relief='flat',
                               command=self.organize_desktop)
        organize_btn.pack(fill='x', pady=2)
        
        show_btn = tk.Button(btn_frame, text="📂 显示分类", font=('微软雅黑', 11, 'bold'),
                           bg='#27ae60', fg='white', relief='flat',
                           command=self.show_categories)
        show_btn.pack(fill='x', pady=2)
        
        hide_btn = tk.Button(btn_frame, text="🙈 隐藏分类", font=('微软雅黑', 11, 'bold'),
                           bg='#f39c12', fg='white', relief='flat',
                           command=self.hide_categories)
        hide_btn.pack(fill='x', pady=2)
        
        restore_btn = tk.Button(btn_frame, text="↩️ 还原桌面", font=('微软雅黑', 11, 'bold'),
                              bg='#9b59b6', fg='white', relief='flat',
                              command=self.restore_desktop)
        restore_btn.pack(fill='x', pady=2)
        
        # 进度条
        self.progress_var = tk.DoubleVar()
        self.progress_bar = ttk.Progressbar(main_frame, variable=self.progress_var,
                                          maximum=100, length=250)
        self.progress_bar.pack(pady=10)
        
        # 初始扫描
        self.scan_desktop()
        
    def start_drag(self, event):
        """开始拖拽"""
        self.is_dragging = True
        self.drag_data["x"] = event.x
        self.drag_data["y"] = event.y
        
    def on_drag(self, event):
        """拖拽中"""
        if self.is_dragging:
            x = self.root.winfo_x() + (event.x - self.drag_data["x"])
            y = self.root.winfo_y() + (event.y - self.drag_data["y"])
            
            # 屏幕边缘吸附
            screen_width = self.root.winfo_screenwidth()
            screen_height = self.root.winfo_screenheight()
            
            # 左右边缘吸附
            if x < 20:
                x = 0
            elif x > screen_width - 300:
                x = screen_width - 280
                
            # 上下边缘吸附
            if y < 20:
                y = 0
            elif y > screen_height - 450:
                y = screen_height - 400
            
            self.root.geometry(f"+{x}+{y}")
            
    def stop_drag(self, event):
        """停止拖拽"""
        self.is_dragging = False
        
    def scan_desktop(self):
        """扫描桌面"""
        try:
            desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
            desktop_files = []
            
            for item in os.listdir(desktop_path):
                item_path = os.path.join(desktop_path, item)
                if os.path.isfile(item_path) and not self._is_system_file(item):
                    desktop_files.append(item)
            
            file_count = len(desktop_files)
            self.status_label.config(text=f"桌面文件: {file_count} 个\n可整理文件: {file_count} 个")
            
        except Exception as e:
            self.status_label.config(text=f"扫描失败: {str(e)}")
            
    def organize_desktop(self):
        """一键整理桌面"""
        if get_setting("confirm_before_organize", True):
            if not messagebox.askyesno("确认整理", "确定要整理桌面吗？\n文件将分类显示在桌面窗格中"):
                return
        
        threading.Thread(target=self._organize_desktop_thread, daemon=True).start()
        
    def _organize_desktop_thread(self):
        """整理桌面线程"""
        try:
            desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
            storage_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "桌面收纳空间")
            backup_path = os.path.join(storage_path, "备份记录")
            
            # 确保目录存在
            os.makedirs(storage_path, exist_ok=True)
            os.makedirs(backup_path, exist_ok=True)
            
            # 获取桌面文件
            desktop_files = []
            for item in os.listdir(desktop_path):
                item_path = os.path.join(desktop_path, item)
                if os.path.isfile(item_path) and not self._is_system_file(item):
                    desktop_files.append(item)
            
            if not desktop_files:
                messagebox.showinfo("提示", "桌面没有需要整理的文件！")
                return
            
            # 创建备份记录
            backup_record = {
                'timestamp': datetime.now().isoformat(),
                'files': [],
                'source': desktop_path
            }
            
            file_categories = get_file_categories()
            total_files = len(desktop_files)
            processed = 0
            
            # 按类型整理文件
            for file in desktop_files:
                file_path = os.path.join(desktop_path, file)
                file_ext = os.path.splitext(file)[1].lower()
                
                # 确定文件分类
                target_category = '其他'
                for category, extensions in file_categories.items():
                    if file_ext in extensions:
                        target_category = category
                        break
                
                # 创建目标目录
                target_dir = os.path.join(storage_path, target_category)
                os.makedirs(target_dir, exist_ok=True)
                
                # 移动文件
                target_path = os.path.join(target_dir, file)
                if os.path.exists(target_path):
                    name, ext = os.path.splitext(file)
                    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                    new_name = f"{name}_{timestamp}{ext}"
                    target_path = os.path.join(target_dir, new_name)
                
                shutil.move(file_path, target_path)
                
                # 记录备份信息
                backup_record['files'].append({
                    'original_path': file_path,
                    'new_path': target_path,
                    'category': target_category
                })
                
                processed += 1
                self.progress_var.set((processed / total_files) * 100)
                self.root.update_idletasks()
            
            # 保存备份记录
            backup_file = os.path.join(backup_path, f"backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json")
            with open(backup_file, 'w', encoding='utf-8') as f:
                json.dump(backup_record, f, ensure_ascii=False, indent=2)
            
            self.progress_var.set(0)
            messagebox.showinfo("整理完成", f"成功整理了 {processed} 个文件！\n点击'显示分类'查看结果")
            
            # 重新加载文件并自动显示分类
            self.load_existing_files()
            self.show_categories()
            self.scan_desktop()
            
        except Exception as e:
            messagebox.showerror("错误", f"整理桌面时出错: {str(e)}")
            self.progress_var.set(0)
            
    def load_existing_files(self):
        """加载已整理的文件"""
        self.organized_files = {}
        storage_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "桌面收纳空间")
        
        if not os.path.exists(storage_path):
            return
            
        for category in os.listdir(storage_path):
            category_path = os.path.join(storage_path, category)
            if os.path.isdir(category_path) and category != "备份记录":
                files = []
                for file in os.listdir(category_path):
                    file_path = os.path.join(category_path, file)
                    if os.path.isfile(file_path):
                        files.append(FileItem(file_path, category))
                
                if files:
                    self.organized_files[category] = files
                    
    def show_categories(self):
        """显示分类窗格"""
        # 关闭现有窗口
        self.hide_categories()
        
        # 重新加载文件
        self.load_existing_files()
        
        if not self.organized_files:
            messagebox.showinfo("提示", "没有已整理的文件！\n请先进行桌面整理。")
            return
        
        # 创建分类窗口
        x_offset = 100
        y_offset = 100
        
        for i, (category, files) in enumerate(self.organized_files.items()):
            x = x_offset + (i % 3) * 220
            y = y_offset + (i // 3) * 320
            
            category_window = CategoryWindow(category, files, self, x, y)
            self.category_windows.append(category_window)
            
    def hide_categories(self):
        """隐藏所有分类窗格"""
        for window in self.category_windows:
            window.window.destroy()
        self.category_windows.clear()
        
    def refresh_category_windows(self):
        """刷新分类窗口"""
        # 重新加载文件数据
        self.load_existing_files()
        
        # 更新现有窗口
        for window in self.category_windows[:]:
            if window.category in self.organized_files:
                window.files = self.organized_files[window.category]
                window.update_file_list()
                window.update_title()
            else:
                # 如果分类为空，关闭窗口
                window.close_window()
                
    def restore_desktop(self):
        """还原桌面"""
        try:
            storage_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "桌面收纳空间")
            backup_path = os.path.join(storage_path, "备份记录")
            
            if not os.path.exists(backup_path):
                messagebox.showinfo("提示", "没有找到备份记录！")
                return
                
            backup_files = [f for f in os.listdir(backup_path) if f.startswith('backup_') and f.endswith('.json')]
            
            if not backup_files:
                messagebox.showinfo("提示", "没有找到备份记录！")
                return
            
            # 选择最新的备份
            backup_files.sort(reverse=True)
            latest_backup = os.path.join(backup_path, backup_files[0])
            
            if messagebox.askyesno("确认还原", "确定要还原到最近一次整理前的状态吗？"):
                with open(latest_backup, 'r', encoding='utf-8') as f:
                    backup_data = json.load(f)
                
                restored_count = 0
                for file_info in backup_data['files']:
                    if os.path.exists(file_info['new_path']):
                        try:
                            shutil.move(file_info['new_path'], file_info['original_path'])
                            restored_count += 1
                        except:
                            pass
                
                # 隐藏分类窗格并刷新
                self.hide_categories()
                self.scan_desktop()
                messagebox.showinfo("还原完成", f"成功还原了 {restored_count} 个文件！")
                
        except Exception as e:
            messagebox.showerror("错误", f"还原桌面时出错: {str(e)}")
            
    def show_settings(self):
        """显示设置窗口"""
        # 这里可以打开设置窗口
        messagebox.showinfo("设置", "设置功能开发中...")
        
    def close_application(self):
        """关闭应用程序"""
        if messagebox.askyesno("确认退出", "确定要退出桌面助手吗？"):
            # 关闭所有分类窗口
            self.hide_categories()
            self.root.destroy()
            
    def _is_system_file(self, filename):
        """判断是否为系统文件"""
        system_files = ['desktop.ini', 'thumbs.db', 'Thumbs.db']
        important_shortcuts = ['回收站', '此电脑', '网络', '控制面板']
        
        if filename in system_files:
            return True
            
        for important in important_shortcuts:
            if important in filename:
                return True
                
        return False
        
    def run(self):
        """运行应用程序"""
        self.root.mainloop()

if __name__ == "__main__":
    app = DesktopManager()
    app.run() 